package jd.client.action;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

import jd.client.Request;
import jd.client.ResponseFactory;

/**
 * @author Denis Migol
 * 
 */
public class ActionAddLinksGrabberRequest extends Request {

	/**
	 * /action/add/links/grabber(0|1)/start(0|1)/%X%
	 */
	public static final String URL = "/action/add/links/grabber";

	private boolean grabber;
	private boolean start;
	private final List<String> links = new LinkedList<String>();

	static {
		ResponseFactory.register(ActionAddLinksGrabberRequest.class, ActionAddLinksGrabberResponse.class);
	}

	/**
	 * The constructor
	 */
	public ActionAddLinksGrabberRequest() {
		super(URL);
	}

	@Override
	public String getUrl() {
		final StringBuilder ret = new StringBuilder(URL);
		ret.append((grabber ? '1' : '0'));
		ret.append("/start" + (start ? '1' : '0') + '/');

		String space = " ";
		try {
			space = URLEncoder.encode(space, "utf8");
		} catch (final UnsupportedEncodingException e) {
		}
		final Iterator<String> iter = links.iterator();
		boolean hasNext = iter.hasNext();
		while (hasNext) {
			ret.append(iter.next());
			hasNext = iter.hasNext();
			if (hasNext) {
				ret.append(space);
			}
		}
		return ret.toString();
	}

	/**
	 * @param grabber
	 *            the grabber to set
	 */
	public ActionAddLinksGrabberRequest setGrabber(final boolean grabber) {
		this.grabber = grabber;
		return this;
	}

	/**
	 * @return the grabber
	 */
	public boolean isGrabber() {
		return grabber;
	}

	/**
	 * @param start
	 *            the start to set
	 */
	public ActionAddLinksGrabberRequest setStart(final boolean start) {
		this.start = start;
		return this;
	}

	/**
	 * @return the start
	 */
	public boolean isStart() {
		return start;
	}

	/**
	 * @return the links
	 */
	public List<String> getLinks() {
		return links;
	}

	/**
	 * 
	 * @param link
	 * @return
	 */
	public ActionAddLinksGrabberRequest addLink(final String link) {
		if ((link != null) && !"".equals(link) && !links.contains(link)) {
			links.add(link);
		}
		return this;
	}

	/**
	 * 
	 * @param links
	 * @return
	 */
	public ActionAddLinksGrabberRequest addLinks(final List<String> links) {
		for (final String link : links) {
			addLink(link);
		}
		return this;
	}
}
